package com.bbs2.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.bbs2.entity.Repost;
import com.bbs2.entity.User;
import com.bbs2.util.DBHelp;
import com.bbs2.util.RowMapper;

public class RepostDao {
	private DBHelp<Repost> db = new DBHelp<Repost>();
	public List<Repost> findByPostId(String id){
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT r.id,content,createTime,r.flag,t_post_id,t_user_id,u.id AS uid,u.name,u.password,u.email,u.flag AS uflag,u.pic,u.regTime ");
		sql.append("FROM t_repost AS r ");
		sql.append("LEFT JOIN t_user AS u ");
		sql.append("ON u.id=r.t_user_id ");
		sql.append("WHERE r.t_post_id=?");
		return db.queryForList(sql.toString(), new RepostMap(), id);
	}
	public int del(String id){
		String sql = "UPDATE t_repost SET flag = 0 WHERE id=?";
		return db.executeUpdate(sql, id);
	}
	public int save(Repost r){
		String sql = "INSERT INTO t_repost(content,createTime,flag,t_post_id,t_user_id) VALUES(?,?,?,?,?)";
		return db.executeUpdate(sql, r.getContent(),r.getCreateTime(),r.getFlag(),r.getPostId(),r.getUserId());
	}
}
class RepostMap implements RowMapper<Repost>{

	public Repost mapRow(ResultSet rs) throws SQLException {
		Repost r = new Repost();
		r.setId(rs.getInt("id"));
		r.setContent(rs.getString("content"));
		r.setCreateTime(rs.getString("createTime"));
		r.setFlag(rs.getInt("flag"));
		r.setPostId(rs.getInt("t_post_id"));
		r.setUserId(rs.getInt("uid"));
		
		User u = new User();
		u.setId(rs.getInt("uid"));
		u.setName(rs.getString("name"));
		u.setPassword(rs.getString("password"));
		u.setEmail(rs.getString("email"));
		u.setFlag(rs.getInt("uflag"));
		u.setPic(rs.getString("pic"));
		u.setRegTime(rs.getString("regTime"));
		
		r.setUser(u);
		return r;
	}
	
}